import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'package:labcloud_app/model/user/user_cart_model.dart';
import 'package:labcloud_app/widget/async_image.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

import '../data/product.dart';
import '../data/user_cart.dart';

class ShoppingCart extends StatefulWidget {
  const ShoppingCart({super.key});

  @override
  State<ShoppingCart> createState() => _ShoppingCartState();
}

class _ShoppingCartState extends State<ShoppingCart> {

  Future<void> _loadShoppingCart() async {
    try {
      final cartModel = context.read<UserCartModel>();
      final client = GraphQLProvider.of(context).value;
      // 重置状态后再加载，确保可以重新加载数据
      cartModel.resetLoadStatus();
      await cartModel.loadCartItems(client);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载购物车失败: $e')),
        );
      }
    }
  }

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      final userCartModel = context.read<UserCartModel>();
      final client = GraphQLProvider.of(context).value;
      userCartModel.loadCartItems(client);
    });
  }


  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('购物车页'),
      ),
      body: Consumer<UserModel>(builder: (context, userModel, child) {
        // 当用户模型初始化完成且用户已登录时，执行加载操作
        // 检查用户是否登录
        if (!userModel.isLoggedIn) {
          return _buildLoginPrompt(context);
        }

        return Consumer<UserCartModel>(builder: (context, cartModel, child) {

          if (cartModel.isLoading) {
            return Center(child: CircularProgressIndicator());
          }

          if (cartModel.errorMessage.isNotEmpty) {
            return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(cartModel.errorMessage),
                    ElevatedButton(
                      onPressed: () {
                        _loadShoppingCart();
                      },
                      child: const Text('重试'),
                    ),
                  ],
                ),
              );
          }

          return _buildContent(userModel, cartModel);
        });

      })
    );
  }

  Widget _buildContent(UserModel userModel, UserCartModel cartModel) {
    if (!cartModel.hasCartItems) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.shopping_cart_outlined,
              size: 80,
              color: Colors.grey,
            ),
            const SizedBox(height: 20),
            const Text(
              '购物车是空的',
              style: TextStyle(
                fontSize: 18,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 30),
            ElevatedButton(
              onPressed: () {
                // 导航到商品页面
                Navigator.pushNamed(context, '/main');
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
              ),
              child: const Text('去逛逛'),
            ),
          ],
        ),
      );
    }

    return Column(
      children: [
        Expanded(
          child: RefreshIndicator(
            onRefresh: () async {
              await _loadShoppingCart();

              if (mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('购物车刷新完成')),
                );
              }
            },
            child: ListView.builder(
                itemCount: cartModel.cart.length,
                itemBuilder: (context, index) {
                  final cartItem = cartModel.cart[index];
                  if (cartItem.product != null) {
                    return _buildProductItem(context, cartItem.product!, cartItem, cartModel);
                  }
                  return Container(); // 如果找不到商品，返回空容器
                }
            ),
          ),
        ),
        // 底部总价栏
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.5),
                spreadRadius: 1,
                blurRadius: 3,
                offset: const Offset(0, -1),
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '总计: ¥${cartModel.totalPrice.toStringAsFixed(2)}',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              ElevatedButton(
                onPressed: () {
                  // 跳转到订单提交页面，并传递购物车信息
                  Navigator.pushNamed(
                    context,
                    '/order_submit',
                    arguments: {
                      'cartItems': cartModel.cart,
                    },
                  );
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
                ),
                child: const Text('结算'),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildLoginPrompt(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.shopping_cart,
            size: 80,
            color: Colors.grey,
          ),
          const SizedBox(height: 20),
          const Text(
            '登录后查看购物车',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 30),
          ElevatedButton(
            onPressed: () {
              Navigator.pushNamed(context, '/login');
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30),
              ),
            ),
            child: const Text(
              '登录/注册',
              style: TextStyle(
                fontSize: 16,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProductItem(BuildContext context, Product product, UserCart cartItem, UserCartModel cartModel) {
    return Card(
      key: ValueKey(cartItem.id),
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: GestureDetector(
          onTap: () {
            Navigator.pushNamed(
              context,
              "/product_detail",
              arguments: {"productId": product.id},
            );
          },
          child: Row(
            children: [
              // 产品图片
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: SizedBox(
                  width: 80,
                  height: 80,
                  child: product.coverAddr != null && product.coverAddr!.isNotEmpty
                      ? AsyncImageWidget(imageUrl: product.coverAddr!)
                      : Container(
                    color: Colors.grey[300],
                    child: const Icon(Icons.image, color: Colors.grey),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              // 产品信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      product.title ?? '未知商品',
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '¥${(double.tryParse(product.price ?? '0') ?? 0).toStringAsFixed(2)}',
                      style: const TextStyle(
                        fontSize: 16,
                        color: Colors.red,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Row(
                      children: [
                        const Text(
                          '数量: ',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey,
                          ),
                        ),
                        IconButton(
                          onPressed: () async {
                            if ((cartItem.quantity?.toInt() ?? 0) > 1) {
                              final client = GraphQLProvider.of(context).value;
                              final success = await cartModel.updateCartItemCount(
                                client,
                                cartItem.id!,
                                (cartItem.quantity?.toInt() ?? 0) - 1,
                              );

                              if (!success && mounted) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(content: Text('更新失败: ${cartModel.errorMessage}')),
                                );
                              }
                            }
                          },
                          icon: const Icon(Icons.remove, size: 18),
                          padding: EdgeInsets.zero,
                        ),
                        Text(
                          '${cartItem.quantity}',
                          style: const TextStyle(
                            fontSize: 14,
                            color: Colors.grey,
                          ),
                        ),
                        IconButton(
                          onPressed: () async {
                            final client = GraphQLProvider.of(context).value;
                            // 先调用服务端更新
                            final success = await cartModel.updateCartItemCount(
                              client,
                              cartItem.id!,
                              (cartItem.quantity?.toInt() ?? 0) + 1,
                            );

                            if (!success) {
                              if (mounted) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(content: Text('更新失败: ${cartModel.errorMessage}')),
                                );
                              }
                            }
                          },
                          icon: const Icon(Icons.add, size: 18),
                          padding: EdgeInsets.zero,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              // 删除按钮
              IconButton(
                onPressed: () async {
                  // 显示确认对话框
                  final shouldDelete = await showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                      title: const Text('确认删除'),
                      content: const Text('确定要从购物车中移除这个商品吗？'),
                      actions: [
                        TextButton(
                          onPressed: Navigator.of(context).pop,
                          child: const Text('取消'),
                        ),
                        TextButton(
                          onPressed: () {
                            Navigator.of(context).pop(true);
                          },
                          child: const Text('确定'),
                        ),
                      ],
                    ),
                  );

                  if (shouldDelete == true && mounted) {
                    final client = GraphQLProvider.of(context).value;
                    // 先调用服务端删除
                    final success = await cartModel.removeFromCart(client, cartItem.id!);
                    // cartModel.loadCartItems(client);
                    // 检查购物车是否为空，如果为空则重置状态
                    if (success && !cartModel.hasCartItems) {
                      // 如果购物车已空，重置购物车状态以便重新加载
                      cartModel.resetCartState();
                    }

                    if (success) {
                      // 注意：removeFromCart已经更新了本地数据，不需要再调用deleteCartItem
                      if (mounted) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('商品已从购物车移除')),
                        );
                      }
                    } else {
                      if (mounted) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text('删除失败: ${cartModel.errorMessage}')),
                        );
                      }
                    }
                  }
                },
                icon: const Icon(Icons.delete, color: Colors.grey),
              ),
            ],
          ),
        ),
      ),
    );
  }
}